﻿using System.Linq;
using System.Threading.Tasks;
using TransformerManager.EF.Database;
using TransformerManager.Shared.Helper;
using TransformerManager.EF.Models;
using Microsoft.EntityFrameworkCore;

namespace TransformerManager.Shared.Servers
{
    public class UserService : IUserService
    {
        private readonly AppDBContext _context;

        public UserService(AppDBContext appDBContext)
        {
            _context = appDBContext;
        }

        public async Task AddRefreshTokenAsync(RefreshToken refreshToken)
        {
            await _context.RefreshTokens
                .AddAsync(refreshToken);
        }

        public async Task<PaginationList<ApplicationUser>> GetUsersInfoAsync(
            string keywords,
            bool onlyLeadEngineer,
            PaginationResourceParameters paginationParams)
        {
            IQueryable<ApplicationUser> users = _context.Users;
            if (!string.IsNullOrEmpty(keywords))
            {
                keywords = keywords.Trim();
                users = users
                    .Where(u => u.UserName.Contains(keywords)
                    || u.RealNameCn.Contains(keywords)
                    || u.RealNameEn.Contains(keywords));
            }

            if (onlyLeadEngineer)
            {
                users = users
                    .Where(u => u.IsLeadEngineer == true);
            }

            var result = users.OrderBy(u => u.RealNameEn);

            return await PaginationList<ApplicationUser>.CreateAsync(
                paginationParams.PageNumber,
                paginationParams.PageSize,
                result);
        }

        public async Task<ApplicationUser> GetUserByIdAsync(string id)
        {
            return await _context.Users
                .Where(u => u.Id == id)
                .FirstOrDefaultAsync();
        }

        public async Task<bool> SaveChangesAsync()
        {
            return (await _context.SaveChangesAsync() >= 0);
        }
    }
}
